package com.itheima.sso.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.model.common.dtos.ResponseResult;
import com.itheima.model.common.enums.AppHttpCodeEnum;
import com.itheima.model.common.pojos.User;
import com.itheima.model.common.utils.AppJwtUtil;
import com.itheima.sso.mapper.SSOMapper;
import com.itheima.sso.service.SSOService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class SSOServiceImpl extends ServiceImpl<SSOMapper,User> implements SSOService {

    private final SSOMapper ssoMapper;

    /**
     * 登录
     * @param user
     * @return
     */
    @Override
    public ResponseResult login(User user) {
        // 1.查询是否存在符合信息的用户
        User userDB = ssoMapper.selectOne(new QueryWrapper<User>().eq("username", user.getUsername()).eq("password", user.getPassword()));
        // 2.判断用户是否存在
        if (userDB == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        // 3.生成JWT令牌
        String token = AppJwtUtil.getToken(Long.valueOf(userDB.getUid()));
        // 4.封装数据
        Map<String,Object> result = new HashMap<>();
        result.put("token",token);
        result.put("user",userDB);
        // 5.返回结果
        return ResponseResult.okResult(result);
    }
}
